package com.tbm.impl.service;

import com.tbm.base.service.CommonService;
import com.tbm.common.util.PageData;
import com.tbm.common.util.SpringUtil;
import com.tbm.common.util.ToolUtil;
import com.tbm.repository.CommonRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/9/14.
 */
@Service
public class CommonServiceImpl implements CommonService  {

    @Autowired
    private CommonRepository commonRepository;


    @Override
    public List<PageData> findAll(Example ex, Pageable pageable,Class clazz) {
        Page commonEntites = commonRepository.findAll(ex,pageable);
        List pageList = new ArrayList();
        List<String> fieldKeyList = new ArrayList<>();
        Field[] declaredFields = clazz.getDeclaredFields();
        for(Field field : declaredFields){
            fieldKeyList.add(field.getName());
        }
        for(Object obj : commonEntites.getContent()){
            PageData pd = new PageData();
            for(String field : fieldKeyList){
                try {
                    Method m = (Method)obj.getClass().getMethod("get" + ToolUtil.getFirstUpper(field));
                    Object temp = m.invoke(obj);
                    //JSONArray.fromObject无法将Null转换，强制将null转成""
                    pd.put(field,temp==null?"":temp);
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
            pageList.add(pd);
        }
        return pageList;
    }

    @Override
    public int count(String repositoryClazz) {
        int count = 0;
        ApplicationContext applicationContext = SpringUtil.getApplicationContext();
        try {
            Class clazz = Class.forName(repositoryClazz);
            Object bean = applicationContext.getBean(ToolUtil.getFirstLower(clazz.getSimpleName()), clazz);
            Method m = (Method)clazz.getMethod("count");
            count = Integer.valueOf(String.valueOf(m.invoke(bean))) ;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return count;
    }

}
